/***************************************************************************
创建者：华磊
 开始时间：               : 2020.1１.1
 copyright            : (C) 深圳市华友高科有限公司
 修改说明：（每次有修改就添加一条，带有 修改人，修改时间，修改描述）
修改人:华磊
修改时间:2020.11.29
修改内容:触发信号,补充port,有三处数据 待定 ,可以通过find找到位置

 ***************************************************************************
 *   用户登录对话框测试用代理类
*                                                                         *
 ***************************************************************************/

#include "delegate.h"
#include <QtCore>
#include <QPalette>
#include <QIntValidator>
#include <QDebug>
#include <iostream>
#include <QtNetwork/QTcpSocket>
#ifdef D_USE_QT5FTP
#include "../qftp/qftp.h"
#else
#include <QFtp>//QT5被移除了,需要自己下载源码.
#endif

#include "ftpdelegate.h"
#include "../FtpManage/ftpmanage.h"
#include "hmicommondefine.h"
#include "instructionEnum.h"

#include "../CommunicateDelegate/filedata.h"
extern FileData fileData;

extern FtpManage *ftpManage;

Delegate::Delegate(CommunicateNormalDelegate *communicateNormalIn, QString versionIn,
                   GlobalData *globalDataIn, GlobalData *ioDataIn, Login *loginViewIn,
                   QObject* parent):QObject(parent)
{
    version=versionIn;
    globalData = globalDataIn;
    ioData = ioDataIn;
    loginView=loginViewIn;

    mountDelegate = new MountDelegate(communicateNormalIn,globalDataIn);
    ftpDelegate = new FtpDelegate;
    controllerIp = "";
    getIPhmi = "";

    ////login 控制 delegate和mainwindow的load;手动切换(下拉选择语言)的时候就直接触发
    QObject::connect(loginView, SIGNAL(controllerLanguageChangedSignal(int)),
                     this, SLOT(changeLanguageSlot(int)));
    QObject::connect(loginView, SIGNAL(controllerLanguageChangedSignal(int)),
                     this, SIGNAL(controllerLanguageChangedSignal(int)));

    initConnect();
    readIniCtrlIP();
}

Delegate::~Delegate()
{}

void Delegate::initConnect()
{
    connect(loginView,SIGNAL(controllerLoginSignal(QVector<int>,QVector<int>,QString,QString,int)),this,
            SLOT(controllerLoginSlot(QVector<int>,QVector<int>,QString,QString,int)));
    connect(loginView,SIGNAL(controllerLoginSignal(QVector<int>,QVector<int>,QString,QString,int)),this,
            SIGNAL(controllerLoginSignal(QVector<int>,QVector<int>,QString,QString,int)));
    connect(loginView,SIGNAL(hmiIpSettingSignal()),this,SLOT(hmiIpSettingSlot()));
    connect(loginView->ipSetDialog,SIGNAL(hmiIpSettingSignal(QString)),this,SLOT(hmiIpSettingSlot(QString)));
//    connect(loginView->loginStatus,SIGNAL(loginErrorInformation(QString)),this,SLOT(loginErrorInformationSlot(QString)));
//    connect(loginView->loginStatus,SIGNAL(scanControllerIp()),this,SLOT(scanControllerIpSlot()));
//    connect(loginView->loginStatus,SIGNAL(clearFindTimerSignal()),this,SLOT(clearFindTimerSlot()));

    connect(this,SIGNAL(mountFileSignal(QStringList,QString)),mountDelegate,SLOT(mountFileAddress(QStringList,QString)));
    connect(this,SIGNAL(signal_hmi_ip_port(QString,int)),mountDelegate,SLOT(slot_hmi_ip_port(QString,int)));

    /**************************************************
     *修改人：        hualei
     *修改日期：   2018-08-22
     * 修改说明:  FTP登录信号关联FtpDelegate登录槽函数
     *
     * ***********************************************/
    connect(this, SIGNAL(loginToFtp(QString,int,QString,QString)), ftpDelegate, SLOT(loginToFtpSlot(QString,int,QString,QString)));
<<<<<<< HEAD
    connect(ftpDelegate, SIGNAL(loginGetDirFinished()), this, SLOT(loginGetConfigFileFinished()),Qt::DirectConnection);
=======

    // 更改为先登录验证,登录成功再FTP下载，故已废弃
    //connect(ftpDelegate, SIGNAL(loginGetDirFinished()), this, SLOT(loginGetConfigFileFinished()),Qt::DirectConnection);
>>>>>>> dev

    // 添加登录失败时，弹出 loginStatus界面
    connect(ftpManage, SIGNAL(isLogined(bool,QString)), this, SLOT(loginStatusSlot(bool,QString)));
    connect(ftpManage, SIGNAL(isConnectToHost(bool,QString)), this, SLOT(connectToHostSlot(bool,QString)));

    mountDelegate->moveToThread(&mountThread);
    mountThread.start();
}

void Delegate::writeIniCtrlIP(QString ip,QString port,int account,QString password,QString lang)
{
    QSettings settings(CTRL_IP_INI_PATH, QSettings::IniFormat); // 当前目录的INI文件
    settings.beginGroup("CtrlIP");
    settings.setValue("ip", ip);
    settings.setValue("port", port);
    settings.endGroup();

    settings.beginGroup("Login");
    settings.setValue("account", QString::number(account));
    settings.setValue("password", password);
    settings.setValue("language", lang);
    settings.endGroup();
}

void Delegate::readIniCtrlIP()
{
    QSettings settings(CTRL_IP_INI_PATH, QSettings::IniFormat);
//    QString filePath="../../data/ctrlIP.ini";
//    QString filePath="G:\\linux-vmware-data\\WinQtProject\\linuxControllerHmi\\trunk\\hmiController\\data\\ctrlIP.ini";
//     QString filePath="G:\\ctrlIP.ini";
//    QSettings settings(filePath, QSettings::IniFormat);

    /**************************************************
     *修改人：        hualei
     *修改日期：   2018-08-21
     * 修改说明: 获取.ini文件中的FTP服务所需参数
     *
     * ***********************************************/
    isUseFtp = settings.value("Login/isUseFtp").toInt();
    ftpUserName = settings.value("Login/ftpUserName").toString();
    ftpUserPasswd = settings.value("Login/ftpPassword").toString();
    ftpPort = settings.value("Login/ftpPort").toInt();

    QString ctrlip = settings.value("CtrlIP/ip").toString();
    QString ctrlport = settings.value("CtrlIP/port").toString();
    QString ctrlgw = settings.value("CtrlIP/gateway").toString();
    QString ctrldns = settings.value("CtrlIP/dns").toString();
    QString hmiip = settings.value("HmiIP/ip").toString();
    QString hmiport = settings.value("HmiIP/port").toString();
    QString hmigw = settings.value("HmiIP/gateway").toString();
    QString hmidns = settings.value("HmiIP/dns").toString();

    qDebug()<<CTRL_IP_INI_PATH<<"ctrl ip   "<<ctrlip;
    qDebug()<<CTRL_IP_INI_PATH<<"ctrl port "<<ctrlport;
    qDebug()<<CTRL_IP_INI_PATH<<"ctrl gw   "<<ctrlgw;
    qDebug()<<CTRL_IP_INI_PATH<<"ctrl dns  "<<ctrldns;
    qDebug()<<CTRL_IP_INI_PATH<<"hmi ip    "<<hmiip;
    qDebug()<<CTRL_IP_INI_PATH<<"hmi port  "<<hmiport;
    qDebug()<<CTRL_IP_INI_PATH<<"hmi gw    "<<hmigw;
    qDebug()<<CTRL_IP_INI_PATH<<"hmi dns   "<<hmidns;

    /********************* FTP *******************/
    qDebug() << CTRL_IP_INI_PATH << "Hmi isUseFtp      :" << isUseFtp;
    qDebug() << CTRL_IP_INI_PATH << "Hmi FtpUserName   :" << ftpUserName;
    qDebug() << CTRL_IP_INI_PATH << "Hmi FtpUserPasswd :" << ftpUserPasswd;
    qDebug() << CTRL_IP_INI_PATH << "Hmi FtpPort :" << ftpPort;


    //更新界面
    loginView->initSetIPFromIni(ctrlip,ctrlport,hmiip,hmiport);
    //设置系统网络
#if BUILD_ARM
    initHmiNetwork(hmiip,hmigw,hmidns);
#endif

    int account = settings.value("Login/account").toInt();
    QString password = settings.value("Login/password").toString();
    int lang = settings.value("Login/language").toInt();
//    QString version = settings.value("Login/version").toString();
    int editLang = settings.value("Login/editLanguage").toInt();
    qDebug()<<CTRL_IP_INI_PATH<<"account  "<<account;
    qDebug()<<CTRL_IP_INI_PATH<<"password "<<password;
    qDebug()<<CTRL_IP_INI_PATH<<"language "<<lang;
    //qDebug()<<CTRL_IP_INI_PATH<<"version "<<version;
    qDebug()<<CTRL_IP_INI_PATH<<"editLang "<<editLang;

    /*目前 暂时使用 宏定义 手动修改内部 */
    /*如果不需要就注释掉这部分便可 */
//    version = HMI_VERSION;
//    qDebug()<<CTRL_IP_INI_PATH<<"version "<<version;
    /*如果不需要就注释掉这部分便可 end*/

    //获取挂载地址 2020.06.05 添加
    mountPath = settings.value("Login/mount").toString();
    qDebug()<<"mount Path : "<<mountPath;

    //更新界面
    loginView->initLoginFromIni(account,password,lang,editLang,version);//上次的权限\上次的密码\上次的语言\版本号码
    //设置系统语言
    //initLanguage(lang);
    //setShowInitialLanguage(lang);//只是刷新 delegate本身的语言 跟loginView无关
    //2017-3-24注释上句 读ini文件只需要获取语言变量
    //在main中 updateShow通过信号槽 控制delegate和mainWinload 语言



#ifndef BUILD_X86_WINDOWS
        usleep(1000000);//1s
#else
        //QThread::msleep(1000);//1000ms
        QWaitCondition wait;
        wait.wait(1000);
#endif

        loginView->updateShow();
}

int Delegate::getShowStyle()
{
    QSettings settings(D_SHOW_STYLE_PATH, QSettings::IniFormat);
    return  settings.value("Common/styleId").toInt();

}

void Delegate::initHmiNetwork(QString ip,QString gateway,QString dns)
{
    QString cmd = "";
    QByteArray cmdArray;
    cmd = "ifconfig eth0 "+ip;
    cmdArray = cmd.toLatin1();
    system(cmdArray.data());

    cmd = "route add default gw "+gateway;
    cmdArray = cmd.toLatin1();
    //system(cmdArray.data());//暂时先不执行

    system("rm /etc/resolv.conf");
    system("touch /etc/resolv.conf");
    cmd = "echo nameserver "+dns+">> /etc/resolv.conf";
    cmdArray = cmd.toLatin1();
    //system(cmdArray.data());//暂时先不执行
}

void Delegate::initLanguage(int lang)
{
    qDebug()<<"select language = "<<lang;
    if(globalData)
    {
//        globalData->lock();
        globalData->currentLanguage = lang;
//        globalData->unlock();

        emit setLanguageSignal(lang);//发送信号 通知控制器 和 HMI自己修改语言
    }
}

void Delegate::controllerLoginSlot(QVector<int> controllerIpAddress,QVector<int> hmiIpAddress,
                                   QString port,QString passwardString,int selectedAccount)
{

    //201912255555
    //如果为本地登录，则不使用ftp
    if(127==controllerIpAddress[0] && 0==controllerIpAddress[1] && 0==controllerIpAddress[2] && 1==controllerIpAddress[3])
    {
        isUseFtp=false;
        qDebug()<<"127本地登录，禁用ftp";
    }
//    loginStatus->show();
    hmiPort = port;
//    Debug_Print("Widget::Widget Current ID:%d",hCurrent);
//    qDebug("controllerLoginSlot");
//    qDebug("selectedAccount:%d",selectedAccount);
//    qDebug("controllerIpAddress:%d .%d .%d .%d",controllerIpAddress[0],controllerIpAddress[1],controllerIpAddress[2],controllerIpAddress[3]);


    //此处 获取golbal用户信息userinfo(),然后emit 如果delegate处理ok,就隐藏所有页面
    //如果处理不ok,触发扫描,显示可登陆的IP
//    QString getIP = "";
    for(int i = 0;i<4;i++)
    {
        if(i == 3){
            controllerIp = controllerIp + QString::number(controllerIpAddress[i]);
        }
        else{
            controllerIp = controllerIp + QString::number(controllerIpAddress[i]) + ".";
        }
    }
    ftpServerIp = controllerIp;
    controllerIp = controllerIp + ":" + port;

//    QString getIPhmi = "";
    for(int i = 0;i<4;i++)
    {
        if(i == 3){
            getIPhmi = getIPhmi + QString::number(hmiIpAddress[i]);
        }
        else{
            getIPhmi = getIPhmi + QString::number(hmiIpAddress[i]) + ".";
        }
    }
//    qDebug()<<getIPhmi;

    //通知所有通信线程更新用户数据
    //globalData->tryLock();
//    globalData->lock();
    UserInfo userInfoIn;
    userInfoIn.account = selectedAccount;
    userInfoIn.ip = getIPhmi.toStdString();       //示教器IP
    userInfoIn.password = passwardString.toStdString();
    userInfoIn.operationSystem = "LINUX";         //待定
    //globalData->userInfo.currentRobotIndex = 1;           //??待定

    globalData->setUserInfo(userInfoIn);

//    globalData->serverIP = controllerIp;
//    globalData->serverIPArray = controllerIp.toLatin1();

    globalData->setServerIp(controllerIp);

    /**************************************************
     *修改人：        hualei
     *修改日期：   2018-08-21
     * 修改说明: 将FTP服务所需参数保存到globalData;
     *
     * ***********************************************/
    globalData->isUseFtpOrNfs = isUseFtp;
    globalData->setFtp(ftpUserName,ftpUserPasswd,ftpPort);
//    globalData->ftpUserName = ftpUserName;
//    globalData->ftpUserPasswd = ftpUserPasswd;
//    globalData->ftpPort = ftpPort;

//    globalData->unlock();
//    loginView->loginStatus->show();
    globalData->isFtpConnectSuccess = false;

<<<<<<< HEAD
    if(globalData->isUseFtpOrNfs)
    {
//        fileData.getMusicFileInfoFlag = false;
//        fileData.getMapFileInfoFlag = false;
        emit loginToFtp(getIP, ftpPort, ftpUserName, ftpUserPasswd);              // FTP
    }
    else
    {
        loginStatus->show();
        globalData->isFtpConnectSuccess = false;

        emit signal_hmi_ip_port(getIPhmi,port.toInt());
=======
    // 挂载
    emit signal_hmi_ip_port(getIPhmi,port.toInt());
>>>>>>> dev
        //    qDebug()<<globalData->userInfo.account;
        //    qDebug()<<QString::fromStdString(globalData->userInfo.ip);
        //    qDebug()<<"*******"<<globalData->serverIP;

    //normal更新用户数据
    //save更新用户数据ip port password
    emit callTmpInfoUpdate(controllerIp);              //待定 这里过度太快,是否需要缓冲一下???

    //connect尝试
    emit tryToConnect_signal(version);

    // 控制器IP登录一次后清除，下一次登录时重新获取
    getIPhmi.clear();
    controllerIp.clear();
//    }

//    emit signal_hmi_ip_port(getIPhmi,port.toInt());
//    qDebug()<<globalData->userInfo.account;
//    qDebug()<<QString::fromStdString(globalData->userInfo.ip);
//    qDebug()<<"*******"<<globalData->serverIP;

//    //normal更新用户数据
//    //save更新用户数据
//    emit callTmpInfoUpdate(getIP);              //待定 这里过度太快,是否需要缓冲一下???
//    //connect尝试
//    emit tryToConnect(HMI_VERSION);

}

void Delegate::recvConnectResult(int result, QString note)
{
    QStringList list = globalData->getServerIp().split(":");

    if(0 == result)
    {
        //登陆许可
#ifdef D_FOR_AGV
#else
        loginView->hide();
#endif


        loginView->loginStatus->hide();

        emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("登录成功!!!"));

        emit loginControllerSucess_signal();

        // FTP登录下载
        if(globalData->isUseFtpOrNfs)
        {
            QString ftpUserNameOut;
            QString ftpUserPasswdOut;
            int portOut;
            globalData->getFtp(ftpUserNameOut, ftpUserPasswdOut, portOut);
            emit loginToFtp(ftpServerIp, portOut, ftpUserNameOut, ftpUserPasswdOut);
        }
        //sleep(1);

        //挂载 nfs
        //emit mountFileSignal(list);

        //记录成功的IP 下次启动按照这个
        writeIniCtrlIP(list[0],list[1],loginView->selectedAccount,loginView->passwardString,QString::number(loginView->selectedLanguage));

        if(loginView->haveEdited)
        {

            fileData.initFileData();//清空文件数据(存在情况:若切换机器人,切换IP地址等)

            loginView->haveEdited = false;
        }

        //设置系统语言
        initLanguage(loginView->selectedLanguage);
        emit setEditLanguageSignal(loginView->editLanguage);//通知 pro更新 编辑语言

        //登陆标志位 global数据
//        globalData->lock();
//        globalData->currentRobotID = 1;//重新初始化机器人信息(这个涉及文件地址获取)
        globalData->gsoapCtrlState = EM_UPDATE_STATUS_LV1;//若是切换角色,则是代表 重新回到LV1(初始登录无实际用处)
        globalData->initCtrlState = EM_UPDATE_STATUS_LV1;
        globalData->initHmiState = EM_UPDATE_STATUS_LV1;
        globalData->mountSuccess = false;
        globalData->controllerIsConnected = EM_CONNECT_SUCCESS;
        globalData->globalLoginStatus = true;
//        globalData->unlock();

       //登录标志 io数据
//        ioData->lock();
//        ioData->currentRobotID = 1;//重新初始化机器人信息(这个涉及文件地址获取)
        ioData->gsoapCtrlState = EM_UPDATE_STATUS_LV1;//若是切换角色,则是代表 重新回到LV1(初始登录无实际用处)
        ioData->initCtrlState = EM_UPDATE_STATUS_LV1;
        //ioData->mountSuccess = false;
        //ioData->initHmiState = EM_CF_OFF;
        ioData->controllerIsConnected = EM_CONNECT_SUCCESS;
        ioData->globalLoginStatus = true;
//        ioData->unlock();

        //挂载 nfs 因为上方有设置为false ,所以挂载需要放后面 2017.05.26
        emit mountFileSignal(list,mountPath);

        emit logInSucessSignal();

//        emit midDelegateUpdateMountSignal();//已经转移hmi comm
    }
    else if(-1 == result)
    {
        if(note == "No route to host")
        {
            emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("ping无效\n请检查网络配置或网线"));
        }
        else
        {
            emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("服务器程序无响应\n请检查服务器IP是否正确\n或服务器是否启动"));
        }
    }
    else if(-100 == result)
    {
         loginView->loginStatus->hide();//不显示 登录扫描
         emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("hmi版本与控制器不兼容，请升级"));

    }
    else//1
    {
        loginView->loginStatus->hide();//不显示 登录扫描
        emit msgBoxSignal(EM_MSG_BOX_SURE_BTN,tr("提示"),tr("登录密码错误"));

        qDebug()<<"login password fail##########################################";
    }
}

bool Delegate::pingTest(QString ip,int port)
{
    QString cmd = "ping -c 1 "+ip;
    QByteArray cmdList = cmd.toLatin1();

    if(0 == system(cmdList.data()))
    {
        return true;//ping 通
    }
    else
    {
        return false;//ping 不通
    }
    //qDebug()<<system("ping -c 1 192.168.1.110");
}

void Delegate::setShowInitialLanguage(int language)
{
    if(1 == language)
    {
        translator.load("/agvwork/AgvHmi/baseBag/hmiProject/language/loginDelEnglishLan.qm");
        qApp->installTranslator(&translator);
    }
    else
    {
        qApp->removeTranslator(&translator);
    }
}

void Delegate::hmiIpSettingSlot()
{
    //qDebug("hmiIpSettingSlot");
    //QMessageBox::information(NULL,"hmiIpSettingSlot","hmiIpSettingSlot",tr("是"),tr("否"));
    //changeLoginViewMember();
    if(loginView->ipSetDialog)
    {
        loginView->ipSetDialog->show();
    }
}

void Delegate::hmiIpSettingSlot(QString ip)
{
    //change system
    QString cmd = "ifconfig eth0 "+ ip;
    QByteArray tmp = cmd.toLatin1();
    system(tmp.data());

    //change ini
    QSettings settings(CTRL_IP_INI_PATH, QSettings::IniFormat); // 当前目录的INI文件
    settings.beginGroup("HmiIP");
    settings.setValue("ip", ip);
    settings.endGroup();

    //change ui
    changeLoginViewMember(ip);
}

void Delegate::changeLoginViewMember(QString ip)
{
    QStringList list = ip.split(".");
    if(list.size() == 4)
    {
        loginView->hmiIpAddress[0]=list[0].toInt();
        loginView->hmiIpAddress[1]=list[1].toInt();
        loginView->hmiIpAddress[2]=list[2].toInt();
        loginView->hmiIpAddress[3]=list[3].toInt();
    }
    loginView->updateShow();
}

void Delegate::loginErrorInformationSlot(QString getIP)
{
    //qDebug()<<"登录成功";
    //QMessageBox::information(NULL,"登录","登录失败","重试","取消");

    globalData->setServerIp(getIP);
//    globalData->serverIP = getIP;
//    globalData->serverIPArray = getIP.toLatin1();

    //normal更新用户数据
    //save更新用户数据
    emit callTmpInfoUpdate(getIP);              //待定 这里过度太快,是否需要缓冲一下???

    //connect尝试
    emit tryToConnect_signal(version);
}

void Delegate::scanControllerIpSlot()
{

    emit tryToFindIP();

}

void Delegate::clearFindTimerSlot()
{
    emit stopFindIP();

    //sleep(1);

    loginView->loginStatus->hide();
}

void Delegate::loginGetConfigFileFinished()
{
    globalData->isFtpConnectSuccess = true;

    emit signal_hmi_ip_port(getIPhmi,hmiPort.toInt());
//    qDebug()<<globalData->userInfo.account;
//    qDebug()<<QString::fromStdString(globalData->userInfo.ip);
//    qDebug()<<"*******"<<globalData->serverIP;

    //normal更新用户数据
    //save更新用户数据
    emit callTmpInfoUpdate(controllerIp);              //待定 这里过度太快,是否需要缓冲一下???

    //connect尝试
    emit tryToConnect_signal(version);

    // 控制器IP登录一次后清除，下一次登录时重新获取
    getIPhmi.clear();
    controllerIp.clear();
}

void Delegate::loginStatusSlot(bool loginResult, QString message)
{
    if(!loginResult)
    {
//        loginView->loginStatus->show();
        qDebug()<<"ftp 登录失败，，，确认用户、密码、网络是否正常。" << message;
    }
    else
    {
        loginView->loginStatus->hide();
    }

}

void Delegate::connectToHostSlot(bool result, QString message)
{
    if(!result)
    {
//        loginView->loginStatus->show();
    }
    else
    {
        loginView->loginStatus->hide();
    }
    qDebug() << message;
}

void Delegate::findIpResultSlot(QVector<QString> findIP)
{
    //qDebug()<<"已找到";
    //只获取前4个

    //loginStatus->controllerIp.resize(findIP.size());

    loginView->loginStatus->controllerIp.clear();
    for(int i = 0;i<findIP.size();i++)
    {
        loginView->loginStatus->controllerIp.append(findIP[i]);
    }
    loginView->loginStatus->foundControllerIpList();
}

void Delegate::changeLanguageSlot(int language)
{
    setShowInitialLanguage(language);
}

